package unique;

//import backup.*;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintStream;
import java.io.InputStream;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.logging.Level;
import java.util.logging.Logger;

public class WebClient {

    private FileHandler cardList;
    private Socket server;
    private String address;
    private int port;

    public WebClient(String name, int port, String archive) { //"archive.txt"
        this.address = name;
        this.port = port;
        /*
         try {
         server = new Socket(name, port);
         } catch (IOException ex) {
         System.err.println("[Client] Error 0x00: Couldn't connect to socket " + port + ".");
         } finally {
         System.out.println("[" + server.getPort() + "] now connected.");
         } //*/
        cardList = new FileHandler(archive);
    }
    
    public void resetCardsList() {
        cardList.resetList();
    }
    
    public void resetFile(){
        cardList.resetFile();
    }

    public void cardIndex() {

        try {
            server = new Socket(address, port);
        } catch (IOException ex) {
            System.err.println("[Client] Error 0x00: Couldn't connect to socket " + port + ".");
        } finally {
            System.out.println("[" + server.getPort() + "] now connected.");
        }

        PrintStream ps = null;
        try {
            ps = new PrintStream(server.getOutputStream());
            InputStream is = server.getInputStream();
            BufferedReader reader = new BufferedReader(new InputStreamReader(is));
            String str = "";
            ps.println("INDEX");
            while ((str = reader.readLine()) != null) {
                System.out.println("cliente: " + str);
                cardList.addCard(str);
            }
        } catch (IOException ex) {
            Logger.getLogger(WebClient.class.getName()).log(Level.SEVERE, null, ex);
        } finally {
            ps.close();
        }
    }

    // Example: Client sends "REMOVE :: 0003" to server. Server removes 0003 then sends "REMOVE :: 0003 completed." to client.
    public void removeCardById(int id) {
//        System.out.println("entour no removecardbyid");
        PrintStream ps = null;
        try {
            server = new Socket(address, port);
        } catch (IOException ex) {
            System.err.println("[Client] Error 0x00: Couldn't connect to socket " + port + ".");
        } finally {
            System.out.println("[" + server.getPort() + "] now connected.");
        }

        String order = "REMOVE :: " + id;
        try {
            // Initial setup
            ps = new PrintStream(server.getOutputStream());
            InputStream is = server.getInputStream();
            BufferedReader reader = new BufferedReader(new InputStreamReader(is));
            
            // Request sending
            ps.println(order);
            System.out.println("[" + server.getPort() + "]" + order);       // debug
            
            // Feedback wait
            while (reader.readLine() != null) continue;
            cardList.removeCardById(id);
            System.out.println("Card #" + id + " removed succesfully.");
        } catch (IOException ex) {
            Logger.getLogger(WebClient.class.getName()).log(Level.SEVERE, null, ex);
        } finally {
            ps.close();
        }
        /*
        try {
            PrintStream ps = new PrintStream(server.getOutputStream());
            InputStream is = server.getInputStream();
            BufferedReader reader = new BufferedReader(new InputStreamReader(is));
            ps.println("REMOVE");
            System.out.println("enviou o remove");
            if (reader.readLine().equals("PRONTO")) {
                System.out.println("enviou o id" + id);
                ps.println(id);
            }
        } catch (IOException ex) {
            Logger.getLogger(WebClient.class.getName()).log(Level.SEVERE, null, ex);
        } finally {
            ps.close();
        }
        /**/

    }

    // Example: Client sends "ADD :: " + card in toString() format. Server then procedes to add such card if it's not on the collection already.
    // Server sends "ADD :: " + id + " completed." to client. 
    public void addCard(String card) throws Exception {
        try {
            server = new Socket(address, port);
        } catch (IOException ex) {
            System.err.println("[Client] Error 0x00: Couldn't connect to socket " + port + ".");
        } finally {
            System.out.println("[" + server.getPort() + "] now connected.");
        }
        
        PrintStream ps = new PrintStream(server.getOutputStream());
        InputStream is = server.getInputStream();
        BufferedReader reader = new BufferedReader(new InputStreamReader(is));

        String order = "ADD :: " + card;

        ps.println(order);
        System.out.println("[" + server.getPort() + "]" + order);       // debug
        while (reader.readLine() != null) {
            continue;
        }
        
        cardList.addCard(card);
        System.out.println("Card #" + Integer.parseInt(card.split(" : ")[0]) + "added succesfully.");
    }

    // Example: Client sends "EDIT :: " + id + " :: " + flavor to server. Server then edits card #id and sends back
    // "EDIT :: " + id + " completed." to client.
    private void editCard(int id, String flavor) throws Exception {
        PrintStream ps = new PrintStream(server.getOutputStream());
        InputStream is = server.getInputStream();
        BufferedReader reader = new BufferedReader(new InputStreamReader(is));

        String order = "EDIT :: " + id + " :: " + flavor;

        ps.println(order);
        System.out.println("[" + server.getPort() + "]" + order);       // debug
        while (reader.readLine() != null) {
            continue;
        }

        System.out.println("Card #" + id + "edited succesfully.");

    }

    public FileHandler getCardList() {
        return cardList;
    }

    public void setCardList(FileHandler cardList) {
        this.cardList = cardList;
    }

    /**
     * M�todo para testar a funcionalidade do servidor Envia repetidamente um
     * conjunto alternado de requisi��es GET e CGI e imprime o resultado na
     * sa�da padr�o.
     *
     * public void run() {
     *
     * }
     *
     * public static void main( String args[]) throws UnknownHostException,
     * IOException {
     *
     * WebClient client = new WebClient(6789); client.run();
     *
     * }
     * /*
     */
}
